package com.lzxuni.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @Description: 处理项目的前台、手机、后台，各自各自的登陆页面或者首页
 * @author 孙志强
 * @date 2017年3月6日 上午10:27:26
 * @version v1.0
 * @since v1.0
 */
public class UrlFilter implements Filter {

	public UrlFilter() {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String uri = httpRequest.getServletPath();
		Boolean flag = true;
		// 静态资源，向下执行
		if (isExinclude(uri)) {
			chain.doFilter(httpRequest, httpResponse);
			return;
		}
		// 默认进项目访问前台登陆页面
		if (uri.equals("/") || uri.equals("") || uri.contains("first.jsp")) {
			uri = "/index.html";
			flag = false ;
		}
		if (flag) {
			chain.doFilter(httpRequest, httpResponse);
			return;
		} else {
			httpResponse.sendRedirect(httpRequest.getContextPath() + uri);
		}
	}

	public void init(FilterConfig filterconfig) throws ServletException {
	}

	/**
	 * 
	 * @Title: isExinclude
	 * @Description: T是否访问静态文件
	 * @author 孙志强
	 * @param uri
	 *            uri链接
	 * @return返回状态
	 */
	private static boolean isExinclude(String uri) {
		String[] exts = new String[] { "jpg", "gif", "js", "png", "css", "doc", "xls", "swf", "ico" };
		for (String ext : exts) {
			if (uri.toUpperCase().endsWith(ext.toUpperCase())) {
				return true;
			}
		}
		return false;
	}

}